#include "BlockQueue.hpp"
#include "Task.hpp"
#include <ctime>
#include <sys/types.h>
#include <unistd.h>

const std::string oper = "+-*/%";

int mymath(int x, int y, char op)
{
    int result = 0;
    switch (op)
    {
    case '+':
        result = x + y;
        break;
    case '-':
        result = x - y;
        break;
    case '*':
        result = x * y;
        break;
    case '/':
    {
        if (y == 0)
        {
            std::cerr << "div zero error!" << std::endl;
            result = -1;
        }
        else
        {
            result = x / y;
        }
    }
    break;
    case '%':
    {
        if (y == 0)
        {
            std::cerr << "mod zero error!" << std::endl;
            result = -1;
        }
        else
        {
            result = x % y;
        }
    }
    break;
    }
    return result;
}

void *consumer(void *bq_)
{
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(bq_);
    while (true)
    {
        // 消费活动
        Task t;
        bq->pop(&t);
        std::cout << "消费任务：" << t() << std::endl;
        // sleep(1);
    }
    return nullptr;
}
void *productor(void *bq_)
{
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(bq_);
    while (true)
    {
        // 生产活动
        int x = rand() % 100 + 1; // 这里我们先用一个随机数构建一个数据。
        int y = rand() % 10;
        int operCode = rand() % oper.size();
        Task t(x, y, oper[operCode], mymath);
        bq->push(t);

        std::cout << "生产任务：" << t.toTaskString() << std::endl;
        sleep(1);
    }
    return nullptr;
}

int main()
{
    srand((unsigned long)time(nullptr) ^ getpid());
    BlockQueue<Task> *bq = new BlockQueue<Task>();
    pthread_t c, c1, p, p1, p2;
    // 生产消费要看到同一份资源，也就是阻塞队列
    pthread_create(&p, nullptr, productor, bq);
    pthread_create(&p1, nullptr, productor, bq);
    pthread_create(&p2, nullptr, productor, bq);

    pthread_create(&c1, nullptr, consumer, bq);
    pthread_create(&c, nullptr, consumer, bq);

    pthread_join(c, nullptr);
    pthread_join(c1, nullptr);
    
    pthread_join(p, nullptr);
    pthread_join(p1, nullptr);
    pthread_join(p2, nullptr);
    delete bq;

    return 0;
}